layui.use(['table', 'layer', 'form', 'jquery', 'element', 'laydate', 'carousel'], function () {
    var table = layui.table;

    var layer = layui.layer;

    var form = layui.form;

    var $ = layui.$;

    var element = layui.element;

    var laydate = layui.laydate;

    var carousel = layui.carousel;

    var nowSelect;


    // 每次会话只打开提示一次
    if (window.sessionStorage.getItem('count') !== '1') {
        $.get('getTeacherEvaluate', function (data) {
            if (data.content === '') {
                window.sessionStorage.setItem('count', '1')
            } else {
                layer.confirm(data.content, {icon: 1, title: '来自butcher：' + data.title}, function (index) {
                    layer.close(index);
                    window.sessionStorage.setItem('count', '1')
                });
            }

        });

    }

    // 以上加载模块

    var members = [];
    var projects = [];
    $.ajax({
        url: 'initData',
        method: 'get',
        success: function (back) {
            members = back.members;
            projects = back.projects;
            getList();
        }
    });


    // 将字符串转为日期
    function strToDate(dateStr) {
        var dateStr = dateStr.replace(/-/g, "/");//现将yyyy-MM-dd类型转换为yyyy/MM/dd
        var dateTime = Date.parse(dateStr);//将日期字符串转换为表示日期的秒数
        //注意：Date.parse(dateStr)默认情况下只能转换：月/日/年 格式的字符串，但是经测试年/月/日格式的字符串也能被解析
        var data = new Date(dateTime);//将日期秒数转换为日期格式
        return data;
    }



    // 生成项目下拉框的方法
    function getList() {

        let sel = $("select[name='projectName']");
        sel.empty();
        $.each(projects, function (i, e) {
            sel.append("<option value=\"" + e.id + "\">" + e.id + "--" + e.name + "</option>");
            sel.val(e.id);
            nowSelect = e.id;
        });
        form.render()
    }



    // 监听项目列表下拉框
    form.on('select(projectSelect)', function (data) {
        table.reload('myTable', {
            url: 'getMsg'
            , where: {pNum: data.value}
            , done: function () {
                nowSelect = data.value;
                getList();
                element.render();
                // 恢复状态
                $("select[name='projectName']").val(data.value);
                form.render();
            }
        });
    });

    // 初始化表格
    table.render({
        elem: '#main',
        url: 'getMsg',
        id: "myTable",
        cols: [[
            {type: "numbers", title: '序号'},
            {field: 'id', hide: true},
            {field: 'name', title: '任务名称', width: 120},
            {field: 'describe', title: '任务描述', width: 450},
            {field: 'responsible', title: '负责人', width: 80},
            {field: 'checkMan', title: '验收人', width: 80},
            {field: 'start', title: '开始日期', width: 120},
            {field: 'end', title: '结束日期', width: 120},
            {title: '操作', width: 170, toolbar: '#rowToolbar'},
            {
                field: 'progress', title: '完成度(上)/时间进度(下)', width: 300, templet: function (d) {
                    let begin = strToDate(d.start).getTime();
                    let nowDate = new Date().getTime();
                    let over = strToDate(d.end).getTime() + (24 * 60 * 60 * 1000);
                    let res = (((nowDate - begin) / (over - begin)) * 100).toString().split('.');
                    let up = '<div class="layui-progress layui-progress-big" lay-filter="proEvent" lay-showPercent="true">' +
                        '		<div class="layui-progress-bar" lay-percent="' + d.progress + '%"></div>' +
                        '	</div>';
                    let down = '<div class="layui-progress layui-progress-big" lay-filter="proEvent" lay-showPercent="true">';
                    if (parseInt(res[0]) > 100) {
                        down += '<div class="layui-progress-bar layui-bg-red" lay-percent="' + res[0] + '%"></div>';
                    } else {
                        down += '<div class="layui-progress-bar layui-bg-blue" lay-percent="' + res[0] + '%"></div>';
                    }

                    down += '</div>';
                    return up + down;
                }
            },
        ]],
        toolbar: '#headToolbar',
        done: function (res, currentCount) {
            element.render();
            carousel.render({
                elem: '#carousel'
                , width: '600px' //设置容器宽度
                , height: '30px'
                , arrow: 'none' //始终显示箭头
                , indicator: 'none'
                , interval: 4000
            });
        },
        size: 'lg'

    });

    table.on('toolbar(mainEvent)', function (obj) {
        if (obj.event === 'add') {
            var index = layer.open({
                title: '添加任务',
                type: 1,
                area: ['400px', '630px'],
                btn: ['我准备好了', '我再想想'],
                yes: function () {
                    let val = form.val('formEvent');
                    // console.log(JSON.stringify(val));
                    $.get('add', {msg: JSON.stringify(val)}, function () {
                        layer.msg("每一个任务都将见证你的成长，回首，你眼里是你的每一次进步！", {icon: 6});
                        layer.close(index);
                        table.reload('myTable', {url: 'getMsg'});
                    });
                },
                btn2: function (index, layero) {
                    layer.msg("让信念坚持下去，梦想就会实现。")
                },
                content: $("#addWindow"),
                success: function () {
                    let sel = $("select[name='responsible']");
                    sel.empty();
                    sel.append("<option value=\"\">请选择你的名字</option>");
                    $("input[name='checkMan']").val(members[0]);
                    $.each(members, function (i, e) {
                        sel.append("<option value=\"" + e + "\">" + e + "</option>")
                    });
                    form.render();
                    laydate.render({
                        elem: '#start' //指定元素
                    });
                    laydate.render({
                        elem: '#end' //指定元素
                    });
                    $("input[name='pid']").val(nowSelect);
                }
            });
        } else if (obj.event === 'setting') {
            layer.prompt({formType: 1, title: '猜猜密码是啥',}, function (value, index, elem) {
                if (value == '654321') {
                    layer.close(index);
                    layer.open({
                        title: '添加项目',
                        type: 1,
                        area: ['400px', '230px'],
                        btn: ['添加项目', '关闭'],
                        yes: function (index, layero) {
                            let val = form.val('addPro');
                            $.get('addProject', val, function () {
                                layer.close(index);
                                $.ajax({
                                    url: 'initData',
                                    method: 'get',
                                    success: function (back) {
                                        members = back.members;
                                        projects = back.projects;
                                        getList();
                                    }
                                });
                                layer.msg("项目添加成功了！", {icon: 1})
                            }).error(function () {
                                layer.msg("失败了，项目可能已存在", {icon: 2})
                            })
                        },
                        btn2: function (index, layero) {
                            layer.msg("新的开始，新的故事，新的拼搏，新的收获，才能铸就新的你。");
                            layer.close(index);
                        },
                        content: $("#setting"),
                        success: function () {
                            form.render();
                        }
                    });
                } else {
                    layer.close(index);
                    layer.msg("密码哪有这么简单~再试试吧！")
                }
            });

        } else if (obj.event === "logout") {
            window.location.href = 'login.html'
        }
    });

    table.on('tool(mainEvent)', function (obj) {
        if (obj.event == 'add') {
            var indexClick = layer.open({
                title: '打卡',
                type: 1,
                area: ['400px', '350px'],
                btn: ['打卡', '我再想想'],
                yes: function () {
                    let val = form.val('clickEvent');
                    let click = JSON.stringify(val);
                    $.get('click', {
                        id: obj.data.id,
                        day: val.day,
                        message: val.message,
                        progress: val.progress
                    }, function (back) {
                        layer.msg("世界之大，必有你的舞台，" + obj.data.responsible + "与B-TEAM同奔赴！");
                        table.reload('myTable', {url: 'getMsg'});
                    });
                    layer.close(indexClick);
                },
                btn2: function (index, layero) {
                    layer.msg("能够坚持，你面对的不会是一帆风顺。")
                },
                content: $("#click"),
                success: function () {
                    form.render();
                    laydate.render({
                        elem: '#day' //指定元素
                    });
                }
            });
        } else if (obj.event == 'look') {
            layer.open({
                title: obj.data.responsible + "的打卡情况",
                type: 1,
                area: '400px',
                offset: '100px',
                content: $("#look"),
                success: function () {
                    var index = layer.load(1);
                    $.get('getDetail', {id: obj.data.id}, function (back) {
                        $("#look").empty();
                        $.each(back, function (i, e) {
                            if (e.evaluateMsg === undefined) {
                                $("#look").append("<blockquote class=\"layui-elem-quote\">" + e.day + "，你完成了：" + e.message + "</blockquote>\n")
                            } else {
                                $("#look").append("<blockquote class=\"layui-elem-quote complete\">" + e.day + "，你完成了：" + e.message + "<br>李伟老师：" + e.evaluateMsg + "</blockquote>\n")
                            }

                        });
                        layer.close(index);
                    });

                }
            });
        } else if (obj.event == 'complete') {
            var index = layer.open({
                title: "口令！",
                content: "<input type=\"text\" id=\"confirm\"  class=\"layui-input\">",
                btn: ["结束"],
                yes: function () {
                    let password = $("#confirm").val();
                    if (password == '') {
                        layer.msg('想偷鸡？');
                    } else if (password == '654321') {
                        $.get('complete', {id: obj.data.id}, function () {
                            layer.msg('又完成了一个任务点，真棒');
                            table.reload('myTable', {url: 'getMsg'});
                            layer.close(index);
                        });
                    } else {
                        layer.msg('再输错一次你的身份将会被敌方知晓！');
                    }

                }
            });


        }
    });
});